package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.CarInformation;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Insurance;
import cn.wolfcode.crm.domain.Product;
import cn.wolfcode.crm.mapper.CustomerMapper;
import cn.wolfcode.crm.mapper.InsuranceMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.ICarInformationService;
import cn.wolfcode.crm.service.IInsuranceService;
import cn.wolfcode.crm.service.IOrganizationService;
import cn.wolfcode.crm.service.IProductService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.RandomUtil;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class InsuranceServiceImpl implements IInsuranceService {

    @Autowired
    private ICarInformationService carInformationService;
    @Autowired
    private InsuranceMapper insuranceMapper;
    @Autowired
    private IOrganizationService organizationService;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private IProductService productService;

    /**
     * 查询保单：暂存/核保单
     */
    @Override
    public PageResult query(QueryObject qo) {
        int rows = insuranceMapper.queryForCount(qo);
        if (rows == 0) {
            new PageResult(rows, Collections.EMPTY_LIST);
        }
        List<Insurance> result = insuranceMapper.queryForList(qo);
        return new PageResult(rows, result);
    }

    /**
     * 保存保单
     */
    @Override
    public void saveOrUpdate(Insurance insurance) {
        /**如果汽车不存在，则保存
         * 判断依据：客户名称、车牌号码
         * */
        //保存汽车
        CarInformation car = carInformationService.getCar(insurance.getCar().getName(), insurance.getCar().getCarnumber());
        if (car == null) {
            car = insurance.getCar();
            CarInformation newcar = carInformationService.get(insurance.getCar().getId());
            newcar.setName(car.getName());
            newcar.setCarnumber(car.getCarnumber());
            newcar.setBegindate(car.getBegindate());
            insurance.setCar(newcar);
            carInformationService.insert(insurance.getCar());
        }
        //保存客户
        if (insurance.getCustomer().getId() == null) {
            customerMapper.insert(insurance.getCustomer());
        }
        //保存产品
        if (insurance.getProduct().getId() != null) {
            insurance.setProduct(productService.get(insurance.getProduct().getId()));
        }
        // 保存机构
        if (insurance.getOrganization().getName() != null) {
            insurance.setOrganization(organizationService.getByName(insurance.getOrganization().getName()));
        }

        //保存保单
        if (insurance.getId() == null) {
            Employee currentUser = UserContext.getCurrentUser();
            insurance.setApplicationDate(new Date());
            insurance.setPayState(false);
            insurance.setSale(currentUser);
            //保单单号
            insurance.setSn(RandomUtil.getRandomSn());
            insuranceMapper.insert(insurance);
        } else {
            Insurance newInsurance = insuranceMapper.selectByPrimaryKey(insurance.getId());
            newInsurance.setCar(insurance.getCar());
            newInsurance.setCustomer(insurance.getCustomer());
            newInsurance.setProduct(insurance.getProduct());
            newInsurance.setOrganization(insurance.getOrganization());
            newInsurance.setBurningTime(insurance.getBurningTime());
            newInsurance.setTotalAmount(insurance.getTotalAmount());
            insuranceMapper.updateByPrimaryKey(newInsurance);
        }
    }

    @Override
    public void deleteByPrimaryKey(Long id) {
        insuranceMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void submitAudit(Long id) {
        insuranceMapper.submitAudit(id);
    }

    /**
     * 待审核页面退回批改单
     */
    @Override
    public void returnApplication(Long id) {

        insuranceMapper.returnApplication(id);
    }

    /**
     * 通过审核，添加审核人、审核单号(如没有)、审核日期、审核编号、生产日期、失效日期、改成保单状态
     */
    @Override
    public void passApplication(Long id) {
        Insurance insurance = insuranceMapper.selectByPrimaryKey(id);
        insurance.setAudit(UserContext.getCurrentUser());
        //保单审核单号
        insurance.setAuditNumber(RandomUtil.getRandomSn());
        //保单开始生产日期
        insurance.setBeginDate(new Date());

        //静态方法getInstance()使用默认时区和语言环境获得一个日历。
        Calendar calendar = Calendar.getInstance();
        //增加保险年限
        calendar.setTime(new Date());
        calendar.add(Calendar.YEAR, insurance.getBurningTime());
        //保单失效日期
        insurance.setEndDate(calendar.getTime());
        /**
         * 点击审核按扭，获取当前用户名称，随机的审核单号，修改当前id的列属性
         *  并将保单状态设为已审核
         *  sn保单编号
         *  auditNumber审核单号
         * */
        /**
         * 案例保单号62170020201806509141204328
         *          62170020201806131158434328
         * */

        //改变保单状态
        insurance.setState(4);
        insuranceMapper.passApplication(insurance);
    }

    @Override
    public Insurance getByIdAndState(Long id, int state) {
        return insuranceMapper.getByIdAndState(id, state);
    }

    @Override
    public Product getProductById(Long id) {
        return insuranceMapper.getProductById(id);
    }

    @Override
    public void payInsurance(Insurance insurance) {
        insuranceMapper.payInsurance(insurance);
    }

}
